package cn.ijero.composeui.page.advanced.banner

import android.content.Context
import android.content.Intent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import cn.ijero.composeui.R
import cn.ijero.composeui.base.BaseActivity
import com.google.accompanist.pager.*
import kotlinx.coroutines.launch
import java.util.*
import kotlin.concurrent.timer
import kotlin.concurrent.timerTask

class BannerActivity : BaseActivity() {
    companion object {
        @JvmStatic
        fun start(context: Context) {
            val starter = Intent(context, BannerActivity::class.java)
            context.startActivity(starter)
        }
    }

    @Composable
    override fun RenderContent() {
        RootLayout()
    }
}


@OptIn(ExperimentalPagerApi::class)
@Composable
private fun RootLayout() {
    val imgs = listOf(R.mipmap.img1, R.mipmap.img2, R.mipmap.img3, R.mipmap.img4)
    val state = rememberPagerState()
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(200.dp),
    ) {
        HorizontalPager(
            modifier = Modifier.fillMaxSize(),
            count = imgs.size,
            state = state
        ) { page ->
            val imgId = imgs[page]
            Image(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(24.dp, 12.dp)
                    .clip(RoundedCornerShape(10.dp)),
                painter = painterResource(id = imgId),
                contentDescription = null,
                contentScale = ContentScale.Crop
            )
        }
        HorizontalPagerIndicator(
            pagerState = state,
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(16.dp),
        )
    }

    StartLoopBanner(state)
}

var timer: Timer? = null

@OptIn(ExperimentalPagerApi::class)
@Composable
private fun StartLoopBanner(state: PagerState) {
    val scope = rememberCoroutineScope()
    timer?.cancel()
    timer = timer(initialDelay = 3000L, period = 3000L) {
        scope.launch {
            state.animateScrollToPage((state.currentPage + 1) % state.pageCount)
        }
    }
}

@Preview(showBackground = true)
@Composable
private fun DefaultPreView() {
    RootLayout()
}